<template>
  <div class="min-box scroll" v-if="addFlowVisible" v-loading="loading">
    <div class="min-title">
      <div class="icon"></div>
      <div class="text">{{ noticeId === 0 ? "流程创建" : "流程编辑" }}</div>
    </div>
    <div class="create-from">
      <el-form ref="formRef" :inline="true" :model="formCustom" status-icon :rules="rules" label-width="auto">
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="formCustom.name" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="关联业务类型" prop="business">
          <el-select ref="type" v-model="formCustom.business" placeholder="请选择" @change="businessChange" multiple>
            <el-option value="通用" label="通用"></el-option>
            <el-option v-for="item in businessList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="设置为默认流程" prop="is_default">
          <el-switch v-model="formCustom.is_default"></el-switch>
        </el-form-item> -->
      </el-form>
    </div>
    <div class="tab-box">
      <div :class="selectFlow === 'operate' ? 'tab-select' : 'tab-text'" @click="selectFlow = 'operate'">业务处理流程</div>
      <div :class="selectFlow === 'review' ? 'tab-select' : 'tab-text'" @click="selectFlow = 'review'">业务审核流程</div>
    </div>
    <div class="flow-box" :class="selectFlow === 'operate' ? '' : 'hid'">
      <div class="flow-title">业务处理流程设置</div>
      <Progress
        :save="saveXml"
        :xml-str="formCustom.operate_content"
        :show-type="'OPERATE'"
        :data="formCustom.operate"
        @submit-node="submitNode"
        @submit-process="submitProcess"
      ></Progress>
    </div>
    <div class="flow-box" :class="selectFlow === 'review' ? '' : 'hid'">
      <div class="flow-title">业务审核流程设置</div>
      <Progress
        :save="saveXml"
        :xml-str="formCustom.review_content"
        :show-type="'REVIEW'"
        :data="formCustom.review"
        @submit-node="submitNode"
        @submit-process="submitProcess"
      ></Progress>
    </div>
    <div class="create-footer">
      <el-button type="primary" @click="submit(formRef)">确定</el-button>
      <el-button @click="closeDialog()">取消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="Workflow">
import { ref, reactive, onMounted } from "vue";
import { createFlow, modifyFlow, getBusinessList, getFlowDetail } from "@/api/modules/workflow/workflowConfig";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Flow } from "@/api/interface/workflow";
import Progress from "@/components/Process/index.vue";
// import type { TabsPaneContext } from "element-plus";
const formRef = ref<FormInstance>();
let loading = ref<boolean>(false);
let noticeId = ref<number>(0);
const selectFlow = ref<string>("operate");
const businessList = ref<any>([]);
const formCustom = reactive({
  name: "",
  business: [] as any[],
  is_default: false,
  operate_content: null,
  review_content: null,
  review: [] as any[],
  operate: [] as any[],
  desc: "-"
});
const rules = reactive<FormRules<typeof formCustom>>({
  name: [
    { required: true, message: "不能为空", trigger: "blur" },
    { required: true, message: "长度需为0~64个字符", min: 0, max: 64, trigger: "blur" }
  ],
  business: [{ required: true, message: "不能为空", trigger: "blur" }]
});
const nodesData = ref<any>([]);
const progressData = ref<any>([]);
const addFlowVisible = ref<boolean>(false);
let saveXml = ref<boolean>(false);
const openDialog = async (flowData?: Flow.ResFlowList) => {
  loading.value = true;
  if (flowData) {
    // 获取详情
    noticeId.value = flowData.id;
    const { data } = await getFlowDetail(noticeId.value);
    formCustom.name = data.name;
    formCustom.business = data.business;
    formCustom.is_default = data.is_default;
    formCustom.operate_content = data.operate_content;
    formCustom.review_content = data.review_content;
    // formCustom.operate = data.operate;
    // formCustom.review = data.review;
    if (data.business.length === 0) {
      formCustom.business = ["通用"];
    } else {
      formCustom.business = data.business.map(item => item.id);
    }
    if (data.operate.length) {
      formCustom.operate = formatNodeData(data, "operate");
    }
    if (data.review.length) {
      formCustom.review = formatNodeData(data, "review");
    }
    console.log("formCustom", formCustom);
  } else {
    // 重置表单
    noticeId.value = 0;
    formCustom.name = "";
    formCustom.business = [];
    formCustom.is_default = false;
    formCustom.operate_content = null;
    formCustom.review_content = null;
    formCustom.review = [];
    formCustom.operate = [];
  }
  loading.value = false;
  addFlowVisible.value = true;
};
const closeDialog = () => {
  selectFlow.value = "operate";
  addFlowVisible.value = false;
  emit("refresh");
};
// const handleClick = (tab: TabsPaneContext, event: Event) => {
//   console.log(tab, event);
// };
// emit
const emit = defineEmits<{
  refresh: [];
}>();

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    // 检查from表单是否填写完成
    saveXml.value = true;
    setTimeout(async () => {
      let params = Object.assign({}, formCustom);
      if (params.business.includes("通用")) {
        params.business = [];
      }
      if (!params.operate_content) {
        ElMessage.error("请绘制业务处理流程图！");
        return;
      }
      ElMessageBox.confirm("请确认是否完成流程图及其节点信息配置！").then(async () => {
        if (noticeId.value) {
          await modifyFlow(noticeId.value, params).catch(e => {
            ElMessage.error("流程图修改失败", e);
          });
          ElMessage.success("流程图修改成功");
          closeDialog();
        } else {
          await createFlow(params).catch(e => {
            ElMessage.error("流程图创建失败", e);
          });
          ElMessage.success("流程图创建成功");
          closeDialog();
        }
      });
      // .catch(() => {})
    }, 500);
  });
};

// 总提交检查是否每个节点信息保存完成，并且流程图绘制完成
const submitNode = async (data: any, type, flow) => {
  nodesData.value = data;
  saveXml.value = false;
  if (type === "OPERATE") {
    formCustom.operate_content = flow.xml;
    formCustom.operate = nodesData.value;
  } else if (type === "REVIEW") {
    formCustom.review_content = flow.xml;
    formCustom.review = nodesData.value;
  }
};

const submitProcess = (data: any) => {
  progressData.value = data;
  console.log(progressData.value);
};

const businessChange = (data: any) => {
  if (data.length) {
    if (data.includes("通用")) {
      businessList.value = [];
      formCustom.business = ["通用"];
    }
  } else {
    getBusinessLists();
  }
};

const getBusinessLists = async () => {
  const params = {
    page: 1,
    page_size: 9999
  };
  const { data } = await getBusinessList(params);
  businessList.value = data["results"];
};

const formatNodeData = (data, type: string) => {
  formCustom[type] = data[type].map(item => {
    return {
      node_id: item.node_id,
      name: item.name,
      type: item.type,
      desc: item.desc,
      receiver: item.receiver,
      approve_type: item.approve_type,
      receive_type: item.receive_type
    };
  });
  return formCustom[type];
};
onMounted(async () => {
  getBusinessLists();
});
defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped>
.min-box {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 24px 24px 0;
}
.hid {
  position: absolute;
  top: -2000px;
  left: 0;
}
:deep() .el-form {
  width: 100%;
}
:deep() .el-select__wrapper {
  min-width: 200px;
}
.create-from {
  display: flex;
  height: 60px;
  margin-bottom: 24px;
  border-bottom: 1px dashed var(--el-border-color);
}
.filter {
  width: 100%;
  height: 500px;
  overflow-y: auto;
  border: none;
  box-shadow: none;
}
.upload-demo {
  margin-top: 5px;
}
.create-footer {
  display: flex;
  align-items: center;
  justify-content: end;
}
.min-title {
  display: flex;
  column-gap: 12px;
  align-items: start;
  height: 36px;
  margin-bottom: 32px;
  border-bottom: 1px solid var(--el-border-color);
  opacity: 0.8;
  .icon {
    width: 4px;
    height: 20px;
    background: var(--el-color-primary);
    border-radius: 0 2px 2px 0;
  }
  .text {
    flex: 1;
    overflow: hidden;
    font-size: 16px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .el-button--primary.is-link {
    margin-top: 4px;
  }
}
.tab-box {
  display: flex;
  align-items: center;
}
.tab-text {
  display: flex;
  align-items: center;
  width: 100px;
  height: 32px;
  padding: 0 10px;
  margin-right: 16px;
  color: var(--el-color-primary);
  cursor: pointer;
  background: var(--el-color-primary-light-9);
  border-radius: 2px;
}
.tab-select {
  display: flex;
  align-items: center;
  width: 100px;
  height: 32px;
  padding: 0 10px;
  margin-right: 16px;
  color: #ffffffff;
  cursor: pointer;
  background: var(--el-color-primary);
  border-radius: 2px;
}
.flow-box {
  display: flex;
  flex-direction: column;
  height: 530px;
  padding: 0 16px;
  margin: 16px 0;
  border: 1px solid var(--el-border-color);
  .flow-title {
    padding: 16px 0;
    font-size: 16px;
    font-weight: 700;
    border-bottom: 1px solid var(--el-border-color);
    opacity: 0.8;
  }
}
</style>
